$(function () {
  let goods_id = $.getParam("goods_id");
  if (!goods_id) location.href = "../html/index.html";
  function getData() {
    let arr = [];
    $.ajax({
      url: "/api/goods.php",
      type: "get",
      dataType: "json",
      async: false,
      data: { goods_id: goods_id },
      success: function (res) {
        if (res.code == 1) {
          arr = res.data;
        }
      },
    });
    arr[0]["num"] = 1;
    return arr;
  }
  let data = getData();
  function render(res) {
    let item = res[0];
    let html = `
            <div class="goods-img">
                <img src="${item.img}" alt="">
            </div>
            <div class="more-img">
                <p class="item"><img class="active" src="${
                  item.img
                }" alt=""></p>
                <p class="item"><img src="${item.img}" alt=""></p>
                <p class="item"><img src="${item.img}" alt=""></p>
                <p class="item"><img src="${item.img}" alt=""></p>
                <p class="item"><img src="${item.img}" alt=""></p>
                <p class="item"><img src="${item.img}" alt=""></p>
            </div>
            <div class="goods-info">
                <div class="goods-header">
                    <div class="goods-price">
                        <span class="new-price"><i>&yen;</i>${
                          item.goods_new_price
                        }</span>
                        <span class="old-price"><i>&yen;</i>${
                          item.goods_price
                        }</span>
                    </div>
                    <div class="shoucang"><img src="../img/shoucang.png" alt="收藏"></div>
                </div>
                <div class="goods-name">${item.goods_name}</div>
                <div class="goods-title">${item.goods_title}</div>
                <div class="line"></div>
                <div class="goods-num">
                    <div class="num-txt">数量</div>
                    <div class="num-opera">
                        <div class="num-group">
                            <span class="reduce disabled" max-num="${
                              item.goods_num
                            }"></span>
                            <div class="num">${item.num}</div>
                            <span class="add" max-num="${
                              item.goods_num
                            }"></span>
                        </div>
                    </div>
                </div>
                <div class="goods-service">
                    ${item.service
                      .split(",")
                      .map((v) => {
                        return `<p class="service-item">${v}</p>`;
                      })
                      .join("")}
                </div>
            </div>
            <div class="pj">

            </div>
            <div class="line"></div>`;
    $(".content").html(html);
  }
  render(data);

  $(".content .more-img").on("click", "img", function () {
    $(this).parent("p").siblings("p").children("img").removeClass("active");
    $(this).addClass("active");
    $(".goods-img img").attr("src", $(this).attr("src"));
  });

  function renderNum(item) {
    $(".num-group").html(`
    <span class="reduce ${
      item.num == 1 ? "disabled" : ""
    }" max-num="${item.goods_num}"></span>
    <div class="num">${item.num}</div>
    <span class="add ${
      item.num == item.goods_num ? "disabled" : ""
    }" max-num="${item.goods_num}"></span>`);
  }

  $(document).on("click", ".num-group .reduce", () => {
    if (data[0].num == 1) return;
    if (data[0].num > 1) data[0].num -= 1;
    renderNum(data[0]);
  });

  $(document).on("click", ".num-group .add", () => {
    if (data[0].num == data[0].goods_num) return;
    if (data[0].num < data[0].goods_num) data[0].num += 1;
    renderNum(data[0]);
  });

  $(".dp").click(() => {
    new Model({
      title: "店铺信息",
      content: data[0].business,
      showCancel: false,
      confirmCallbak: function () {
        this.close();
      },
    }).init();
  });

  $(".gwc").click(() => {
    location.href = "../html/cart.html";
  });

  $(".addcart").click(() => {
    let cart = localStorage.getItem("cart");
    if (!cart) localStorage.setItem("cart", JSON.stringify([]));
    cart = JSON.parse(localStorage.getItem("cart"));
    let goods = cart.filter((item) => {
      return item.goods_id == data[0].goods_id;
    });
    if (goods.length == 0) {
      let user_id = null;
      let user = localStorage.getItem("user");
      if (user) {
        user = JSON.parse(user);
        user_id = user.user_id;
      }
      cart.push({
        user_id: user_id,
        goods_id: data[0].goods_id,
        cart_num: data[0].num,
        total: data[0].num * data[0].goods_new_price,
      });
    } else {
      cart.forEach((item) => {
        if (item.goods_id == data[0].goods_id) {
          item.cart_num += data[0].num;
          item.total = item.cart_num * data[0].goods_new_price;
        }
      });
    }
    localStorage.setItem("cart", JSON.stringify(cart));
    renderTag();
  });

  function renderTag() {
    $(".tag").hide();
    $(".tag").text(() => {
      let cart = localStorage.getItem("cart");
      if (!cart) {
        $(this).hide();
        return;
      }
      cart = JSON.parse(cart);
      let count = cart.reduce((pre, item) => {
        return pre + item.cart_num;
      }, 0);
      if (count > 0) $(".tag").show();
      return count;
    });
  }
  renderTag();

  $(".buy").click(() => {
    const login_state = "LOGIN_STATE";
    let state = getCookie(login_state);
    if (!(state && state == "OK")) {
      localStorage.setItem("user", "");
      new Model({
        title: "信息",
        content: "您还没有登录，是否去登录？",
        skin: "tan" /* 主题色 "#20222A"|"#1E9FFF"|"tan" */,
        confirmCallbak: function () {
          location.href = "../html/login.html";
        },
      }).init();
      return;
    }

    let user = localStorage.getItem("user");
    if (!user) {
      clearCookie(login_state);
      location.reload();
    }
    user = JSON.parse(user);
    let userid = user.user_id;
    let total = data[0].num * data[0].goods_new_price;
    let obj = {
      cart_id: 0, //直接购买没有购物车信息
      user_id: userid,
      goods_id: data[0].goods_id,
      cart_num: data[0].num,
      total: total,
      img: data[0].img,
      name: data[0].goods_name,
      price: data[0].goods_new_price,
    };

    let arr = [];
    arr.push(obj);

    let order = {
      user_id: userid,
      total: total,
      data: arr,
    };
    console.log(order);
    sessionStorage.setItem("order", JSON.stringify(order));
    location.href = "../html/order.html";
  });

  // {"user_id":"1","total":115,
  // "data":[{"cart_id":"15","user_id":"1","goods_id":"153","cart_num":"1",
  // "total":115,"img":"https://img.youpin.mi-img.com/shopmain/345909214815ed29909b7f7cee2fd6c5.png?w=800&h=800",
  // "name":"原木结团猫砂","price":"115.00"}]}
});
